<template>
	<view class="">
		<template v-if="$slots.default">
			<u-upload :accept='accept' :fileList="fileList" :name='name' :width='width' :height='height'
				@afterRead="afterRead" @delete="deletePic" :multiple='multiple' :maxCount="maxNum"
				:uploadText='uploadText'>
				<template>
					<slot />
				</template>
			</u-upload>
		</template>

		<template v-else>
			<u-upload :accept='accept' :fileList="fileList" :name='name' :width='width' :height='height'
				@afterRead="afterRead" @delete="deletePic" :multiple='multiple' :maxCount="maxNum"
				:uploadText='uploadText'>
			</u-upload>
		</template>
	</view>

	<!-- 	使用
	<uploadImg ref='uploadImg' @changeImg='changeImg' :maxNum='10' :name='index'
		:fileLists='fileLists'>
	</uploadImg>
	

	changeImg(e) { //上传
	// console.log(e);
	   this.code = e.code
	   this.images = e.img_str
	   
	   this.from.images = e.img_str
	   this.from.flair[e.name].image = images
	},
	
	上传提交判断
	submlie() {
		if (this.code == 100) {
			uni.$u.toast('请等待图片上传完成！')
		} else {
			uni.$u.toast('图片上传完成')
		})
	
	清空上传的图片
	this.$refs.uploadImg.carImg()
	 -->
</template>

<script>
	/*
	 * @param {accept,String} 上传组件标识 all | media | image | file | video,file只支持H5（只有微信小程序才支持把accept配置为all、media）
	 * @param {name,String} 上传组件标识
	 * @param {maxNum,Number} 最多几张图片
	 * @param {uploadText,String} 上传提示文字
	 * @param {multiple,Boolean} 是否开启多图上传 
	 * @param {isProgress,Boolean} 是否开启上传进度显示
	 */
	import {
		mapGetters,
		mapState
	} from 'vuex';
	export default {
		props: {
			accept: {
				typeof: String,
				default: () => 'image'
			},
			fileLists: {
				default: () => []
			},
			name: {
				default: () => ''
			},
			maxNum: {
				default: () => 3
			},
			uploadText: {
				typeof: String,
				default: () => '上传图片'
			},
			multiple: {
				typeof: Boolean,
				default: () => true,
			},
			width: {
				typeof: String,
				default: () => '160rpx'
			},
			height: {
				typeof: String,
				default: () => '160rpx'
			},
			isProgress: {
				typeof: Boolean,
				default: () => false
			}
		},
		components: {},
		data() {
			return {
				fileList: [], //上传图片预览图
			}
		},
		mounted() {

		},
		methods: {
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				let img_arr = []

				this.fileList.map(item => {
					img_arr.push(item.urla)
				})

				let obj = {
					code: 200,
					images: this.fileList,
					name: event.name,
					img_arr: img_arr,
					img_str: img_arr.toString()
				}
				this.$emit('changeImg', obj)
			},
			// 新增图片 
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中',
						code: 100
					})
				})


				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					if (result) {
						this.fileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result ? this.$http + result : '',
							urla: result,
							code: 200,
						}))
					} else {
						this.fileList.splice(fileListLen, 1)
						continue
					}
					fileListLen++
				}

				let img_arr = []
				let flag = this.fileList.every(item => {
					return item.code == 200
				})

				this.fileList.map(item => {
					img_arr.push(item.urla)
				})
				let obj = {
					code: 200,
					images: this.fileList,
					name: event.name,
					img_arr: img_arr,
					img_str: img_arr.toString()
				}

				if (flag) {
					this.$emit('changeImg', obj)
				}

			},
			uploadFilePromise(url) { //上传图片
				return new Promise((resolve, reject) => {
					const downloadTask = uni.uploadFile({
						url: `${this.$http}${this.$uploadUrl}`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							// "Content-Type": "multipart/form-data", //h5上传注释
							'Authorization': this.token
						},
						success: (res) => {
							setTimeout(() => {
								let resa = JSON.parse(res.data)
								if (resa.code == this.status_code) {
									resolve(resa.url)
								} else {
									uni.$u.toast(resa.msg)
									resolve('')
								}
							}, 500)
						},
						fail: (err) => {
							// console.log(err,'===');
							uni.$u.toast('上传失败')
							resolve('')
						},
						complete: () => {
							uni.hideLoading();
						}
					});

					downloadTask.onProgressUpdate((res) => {
						// console.log(res);
						if (res.progress > 0) {
							if (this.isProgress) {
								uni.showLoading({
									title: `上传中${res.progress}%`
								})
								if (res.progress == 100) {
									uni.hideLoading();
								}
								setTimeout(() => {
									uni.hideLoading();
								}, 1000 * 60 * 2)
							}
						}
					})
				})
			},
			carImg() { //清空图片
				this.fileList = []
			},
		},
		computed: {
			...mapState({
				token: 'token'
			})
		},
		watch: {
			fileLists: {
				handler(news, old) {
					let images = JSON.parse(JSON.stringify(this.fileLists))
					let flag = Array.isArray(images)
					let img_list = flag ? images : images ? images.split(',') : []
					let arr = []
					img_list.map(item => {
						let active = /(http|https):\/\/\S+/g.test(item)
						let url = active ? item : this.$http + item
						let urla = active ? item : this.$http + item
						arr.push({
							url: url,
							urla: urla,
							code: 200
						})
					})
					this.fileList = arr
					// console.log(arr,'==');
				},
				deep: true,
				immediate: true
			},
		}
	}
</script>

<style lang="scss" scoped>

</style>